﻿using ApiData.JsonDB;
using Newtonsoft.Json.Linq;
using SqlSugar;

namespace ApiData.Logic
{
    public class Page
    {
        public static Common.ResultData Execute(Model.tables tab, string? page, string size = "10")
        {
            var path = tab.jsondata;
            var phy = Directory.GetCurrentDirectory();
            var real = phy + path;
            var cols = tab.structure.Split("\r\n", StringSplitOptions.RemoveEmptyEntries);
            if (size.IsNullOrWhiteSpace())
                size = "10";

            List<Model.Dto.Structure> st = new List<Model.Dto.Structure>();
            if (!tab.structure.IsNullOrWhiteSpace())
                foreach (var item in cols)
                {
                    if (item.IsNullOrWhiteSpace()) continue;
                    var col = item.Split('-');
                    st.Add(new Model.Dto.Structure()
                    {
                        name = col[0],
                        type = col[1],
                        defaultvalue = col[2],
                        des = col[3]
                    });
                }
            var db = new InitDB(real);
            int count = 0;
            if (page.IsNullOrWhiteSpace())
            {
                count = db.Count();
                return new Common.ResultData().SuccessData(count);
            }

            var data = new object();

            int pageIndex = 0, pageSize = 10;
            if (!Int32.TryParse(page, out pageIndex))
                return new Common.ResultData().Fail("页索引输入错误");
            if (!Int32.TryParse(size, out pageSize))
                return new Common.ResultData().Fail("页大小输入错误");

            data = db.Page(pageIndex, pageSize);
            count = db.Count();

            if (data == null)
                return new Common.ResultData().Fail("找不到相关信息");
            else
                return new Common.ResultData().SuccessData(count, data);
        }
    }
}